<template>
	<view class="wrap">
		<view class="cell">
		  <view class="label">送货上门</view>
		  <switch :checked="delivery" @change="deliveryChange"/>
		</view>
    <view class="cell border-top">
      <view class="label">上门取货</view>
      <switch :checked="colectHome" @change="colectHomeChange"/>
    </view>
		<view class="cell border-top" @click="toSelectAddress" v-if="delivery || colectHome">
		  <view class="label" v-if="order.address.realName">
		    <view class="location-detail bold ellipsis">{{order.address.province}}{{order.address.city}}{{order.address.district}}{{order.address.address}}</view>
		    <view class="phone">{{order.address.realName}}（先生） {{order.address.phone}}</view>
		  </view>
		  <view class="label" v-else>
		    <text>请选择地址</text>
		  </view>
		  <text class="iconfont icon-xiangyou"></text>
		</view>
    <view class="item">
      <view class="title">
        <view class="name">
          <image :src="order.logo" mode="aspectFill" />{{order.shopName}}</view>
        <text class="status">{{['待支付', '待提货', '待归还', '已完成'][item.status - 1]}}</text>
      </view>
      <checkbox-group @change="onRadioGroupChange" v-model="checkedGoods">
        <view class="goods" v-for="(goods, index) in order.goodsArr" v-key>
          <checkbox :value="index"></checkbox>
          <view class="main">
            <image :src="goods.pic" mode="aspectFill"></image>
            <view class="info">
              <view class="name ellipsis-2">{{goods.goodsName}}</view>
              <view class="price">¥{{goods._price}}<text>¥{{goods._deposit}}押金</text></view>
              <view class="shipping-fee">运费：¥{{goods._shippingFee}}</view>
            </view>
          </view>
        </view>
      </checkbox-group>
    </view>
    <view class="btn">
      <view class="count">合计:<text>¥{{total}}</text></view>
      <view class="submit" @click="submit">提交订单</view>
    </view>
	</view>
</template>

<script>
  import {Order, User} from '@/apis'
  import {numeral, utils} from '@/utils'
  
	export default {
    watch: {
      checkedGoods () {
        this.calculateMoney()
      },
      delivery () {
        this.calculateMoney()
      },
      colectHome () {
        this.calculateMoney()
      }
    },
		data() {
			return {
				delivery: false, // 是否送货上门
        colectHome: false, // 是否上门取货
				order: {
				  goods: [],
				  address: {}
				},
        total: 0,
        checkedGoods: []
			}
		},
    computed: {
    },
		methods: {
			toSelectAddress () {
			  uni.navigateTo({
			    url: '/pages/myAddress/myAddress?type=select'
			  })
			},
      onRadioGroupChange (e) {
        this.checkedGoods = e.detail.value
      },
      colectHomeChange (e) {
        this.colectHome = e.detail.value
      },
      calculateMoney () {
        let total = 0
        this.checkedGoods.map(index => {
          let item = this.order.goodsArr[index]
          // 付款金额等于： 一天的租金 + 押金 + 上门取货运费 + 送货上门运费
          total += (numeral(item.price).add(item.deposit)).value()
          // 判断送货上门
          if (this.delivery) total += item.shippingFee
          // pand上门取货
          if (this.colectHome) total += item.shippingFee
        })
        this.total = numeral(total).divide(100).format('0.00')
        this.order.total = this.total
      },
      getOrderDetail () {
        if (this.isLoading) return
        this.isLoading = true
        uni.showLoading({
          title: '加载中...',
          mask: true
        })

        Order.getOrderDetail({
          data: {
            form: {},
            pagination: {},
            query: {
              orderNumber: this.$mp.query.number
            }
          }
        }).then(res => {
          console.log('获取订单详情成功')
          console.log(res.data);
          if (res.data.code !== 200) {
            this.message = res.data.message
            uni.showToast({
              title: res.data.message || '订单异常',
              icon: 'none'
            })
            return
          }
          let order = res.data.body
          let total = 0, totalDeposit = 0, totalPrice = 0
          order.goodsArr.map(item => {
            totalPrice += item.price
            totalDeposit += item.deposit
            // 计算价格、押金
            item._price = numeral(item.price).divide(100).format('0.00')
            item._deposit =  numeral(item.deposit).divide(100).format('0.00')
            item._shippingFee = numeral(item.shippingFee).divide(100).format('0.00')
          })
          
          order.total = numeral(totalPrice).add(totalDeposit).format('0.00')
          order._total = numeral(totalPrice).add(totalDeposit).divide(100).format('0.00')
          order.totalPrice = numeral(totalPrice).divide(100).format('0.00')
          order.totalDeposit = numeral(totalDeposit).divide(100).format('0.00')
          
          this.order = order
          
        }, err => console.error(err)).finally(() => {
          this.isLoading = false
          uni.hideLoading()
        })
      },
      deliveryChange (e) {
        console.log('是否配送', e)
        this.delivery = e.detail.value
      },
      submit () {
        console.log('点击提交订单')
        if (!this.checkedGoods.length) {
          uni.showToast({
            title: '请选择商品',
            icon: 'none'
          })
          return
        }
        // 发起支付
        this.pay()
      },
      pay () {
        let that = this
        // 判断是否选择了地址
        if ((this.delivery || this.colectHome) && !this.order.address) {
          uni.showToast({
            title: '请选择地址',
            icon: 'none'
          })
          return
        }
        if (this.isLoading) return
        this.isLoading = true
        utils.wxLoading()
        const userInfo = uni.getStorageSync('userInfo')
        const outTradeNo = utils.randomWord(false, 32)
        console.log('生成订单号： ' + outTradeNo)
        console.log(this.order)
        let item = utils.deepClone(this.order)
        User.prePayment({
          data: {
            form: {
              device_info: "1",
              body: "商品描述",
              detail: "商品详情",
              out_trade_no: item.orderNumber,
              total_fee: numeral(item.total).multiply(100).value(),
              spbill_create_ip: "0.0.0.0",
              time_start: Date.now(),
              notify_url: "http://www.weixin.qq.com/wxpay/pay.php",
              product_id: utils.randomWord(false, 16),
              openid: userInfo.openid
            }
          }
        }).then(res => {
          console.log('请求支付接口')
          console.log(res)
          let result = res.data.body
          uni.requestPayment({
            nonceStr: result.nonceStr,
            timeStamp: result.timeStamp,
            package: result.packageInfo,
            paySign: result.sign,
            signType: 'MD5',
            success (payRes) {
              console.log('支付完成')
              console.log(payRes)
              Order.updateOrder({ data: {
                form: {
                  updateTime: utils.formatTime(new Date()),
                  orderNumber: item.orderNumber,
                  outTradeNumber: outTradeNo,
                  payTotal: numeral(item.total).multiply(100).value(),
				  colectHome: Number(that.colectHome),
				  provdHome: Number(that.delivery),
                  status: 2,
                  addressId: item.address ? item.address.id : null
                },
                query: {},
                pagination: {}
              }}).then(res => {
                uni.showToast({
                  title: '支付完成',
                  icon: 'success'
                });
                console.log('更新支付状态', res)
                // 清空购物车
                uni.setStorageSync('carGoods', [])
                uni.setStorageSync('shopInfo', null)
                utils.routerBack()
              }).catch(err => console.log(err))
            },
            fail: (err) => {
              console.log('支付失败');
              console.error(err)
              this.isLoading = false
              uni.hideLoading()
              utils.wxToastFail('放弃支付')
            },
            complete () {
              uni.hideLoading()
            }
          })
        }).catch(err => {
          utils.wxToastFail('支付失败')
        }).finally(() => {
          this.isLoading = false
        })
      }
		},
    mounted () {
      this.getOrderDetail()
    },
    onShow () {
      // this.getOrderDetail()
    }
	}
</script>

<style lang="scss">
  page {
    background-color: #EFEFEF;
  }
  .cell {
    box-sizing: border-box;
    padding: 30rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 1rpx;
    background-color: #FFF;
    .label {
      color: #333333;
      font-size: 28rpx;
      .location-detail {
        font-weight: bold;
        max-width: 70%;
      }
    }
    .value {
      flex: 1;
      font-size: 28rpx;
    }
    .time {
      color: #0CB9F2;
      text-align: right;
    }
  }
  .border-top {
    border-top: #EFEFEF 1rpx solid;
  }
  .border-bottom {
    border-bottom: #EFEFEF 1rpx solid;
  }
  .item {
    box-sizing: border-box;
    margin-top: 20rpx;
    padding: 0 20rpx;
    background-color: #FFF;

    .title {
      color: #333333;
      font-size: 30rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: #EFEFEF 1rpx solid;
      padding: 20rpx 0;

      .name {
        display: flex;
        align-items: center;

        image {
          width: 44rpx;
          height: 44rpx;
          margin-right: 20rpx;
          background-color: #D8D8DD;
          border-radius: 50%;
        }
      }

      .status {
        font-weight: normal;
        color: #FF4A4A;
      }
    }
    .goods {
      display: flex;
      align-items: center;
    }
    .main {
      box-sizing: border-box;
      padding: 20rpx 0;
      display: flex;
      flex: 1;
      image {
        flex-shrink: 0;
        width: 140rpx;
        height: 140rpx;
        border-radius: 10rpx;
        background-color: #D8D8D8;
      }

      .info {
        flex: 1;
        box-sizing: border-box;
        padding-left: 20rpx;

        .name {
          color: #333333;
          font-size: 24rpx;
          height: 74rpx;
          line-height: 1.5;
        }

        .price {
          color: #FF4A4A;
          font-size: 24rpx;
          box-sizing: border-box;
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-weight: bold;

          text {
            color: #666;
            padding-left: 30rpx;
          }
        }
        .shipping-fee {
          font-size: 24rpx;
          color: #999;
        }
      }
    }

    .btn-group {
      display: flex;
      align-items: center;
      box-sizing: border-box;
      padding: 20rpx 0;
      border-top: #EFEFEF 1rpx solid;
      flex-direction: row-reverse;

      .total {
        color: #333333;
        font-size: 24rpx;
        line-height: 40rpx;
        flex-justify-self: flex-end;
        margin-right: auto;

        .total-price {
          text {
            color: #FF4A4A;
          }
        }

        .count {
          color: #666;
        }
      }

      button {
        width: 120rpx;
        height: 58rpx;
        border: #FF4A4A 2rpx solid;
        border-radius: 29rpx;
        margin: 10rpx;
        color: #FF4A4A;
        font-size: 28rpx;
        line-height: 58rpx;
        background-color: #FFF;
      }
    }
  }
  .amount-info {
    font-size: 28rpx;
    color: #333333;
    display: flex;
    align-items: center;
    justify-content: space-between;
    text {
      font-weight: bold;
      padding-right: 20rpx;
    }
  }
  .order-info {
    color: #333333;
    font-size: 28rpx;
  }
  .mt {
    margin-top: 20rpx;
  }
  .message {
    color: #999999;
    font-size: 18px;
    line-height: 36px;
    text-align: center;
    padding-top: 100px;
  }
  .btn {
    position: fixed;
    left: 26rpx;
    right: 26rpx;
    bottom: 30rpx;
    border-radius: 50rpx;
    height: 100rpx;
    display: flex;
    align-items: center;
    background-color: #222222;
    color: #FFFFFF;
    .count {
      flex: 1;
      box-sizing: border-box;
      padding-left: 56rpx;
      font-size: 24rpx;
      line-height: 100rpx;
      text {
        font-size: 40rpx;
        padding-left: 20rpx;
      }
    }
    .submit {
      width: 190rpx;
      height: inherit;
      line-height: 100rpx;
      background-color: #FF4A4A;
      font-size: 30rpx;
      text-align: center;
      border-top-right-radius: 50rpx;
      border-bottom-right-radius: 50rpx;
    }
  }
</style>

